/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-07-22     acer       the first version
 */
#include "mqtt2rtu.h"
#include <stdio.h>
#include <stdint.h>

#include "mqttclient.h"
#include "setting.h"
#include "cJSON.h"
#include "tiny_sha1.h"
#include <dfs_posix.h> /* 当需要使用文件操作时，需要包含这个头文件 */

/* 添加 DEBUG 头文件 */
#define DBG_SECTION_NAME               "m2r"
#define DBG_LEVEL                      DBG_INFO
#include <rtdbg.h>

mqtt_client_t *my_client = NULL;

static char *host = RT_NULL;
static char *client_id = RT_NULL;
static char *user_name = RT_NULL;
static char *password = RT_NULL;
static char *publish_addr = RT_NULL;
extern device_param_t device_setting;

/*************************************************
Function:       hex2string
Description:    hex字符数组转换成string字符串，用于printf显示等
Input:          hex:原字符数组
                len:hex数组的长度
Output:         ascII:输出的字符串
                newlen:输出的字符串长度
Return:
*************************************************/
void hex2string(char *hex,char *ascII,int len,int *newlen)
{
    int i = 0;
    char newchar[100] = {0};
    *newlen=len*2;
    for (i = 0; i< len; i++)
    {
        sprintf(newchar,"%02x", hex[i]);
        strcat(ascII, newchar);
    }
}

static void user_get_handle(void* client, message_data_t* msg)
{
    (void) client;
    MQTT_LOG_I("-----------------------------------------------------------------------------------");
    MQTT_LOG_I("%s:%d %s()...\ntopic: %s\nmessage:%s", __FILE__, __LINE__, __FUNCTION__, msg->topic_name, (char*)msg->message->payload);
    MQTT_LOG_I("-----------------------------------------------------------------------------------");
}


static int mqtt_publish_handle1(mqtt_client_t *client)
{
    mqtt_message_t msg;
    memset(&msg, 0, sizeof(msg));

    msg.qos = 1;
    msg.payload = (void *) "user_post_handle";

    char addr[256];
    rt_sprintf(addr, "/user/update");

    return mqtt_publish(client, addr, &msg);
}

void mqtt2rtu_init(void)
{
    switch (device_setting->platform_type)
    {
        case PLATFORM_TYPE_MY:
        {
            my_login();
            break;
        }
        case PLATFORM_TYPE_ALIYUN:
        {
            aliyun_login();
            break;
        }
        case PLATFORM_TYPE_CTWING:
        {
            break;
        }
        case PLATFORM_TYPE_ONENET:
        {
            break;
        }
        default:
            break;
    }
}

void my_login(void)
{
}

void aliyun_login(void)
{
    int fd, size;
    char *buffer = RT_NULL;
    int ret;
    char device_name[33];
    char product_key[64];
    char device_secret[64];
    char region[64];
    struct stat buf;

    cJSON *root = RT_NULL;

    ret = stat("/aliyun.json", &buf);
    if(ret == 0)
    {
        buffer = rt_malloc(buf.st_size);
        /* 以只读模式打开文件 */
        fd = open("/aliyun.json", O_RDONLY);
        if (fd >= 0)
        {
             size = read(fd, buffer, buf.st_size);
             close(fd);
             if (size < 0)
             {
                 goto __mqtt_config_exit;
             }
             root = cJSON_Parse(buffer);
             if(buffer)
             {
                 rt_free(buffer);
                 buffer = RT_NULL;
             }
             if (!root)
             {
                 LOG_E("Error before: [%s]\n",cJSON_GetErrorPtr());
                 goto __mqtt_config_exit;
             }
             else
             {
                 host = rt_malloc(50);
                 if (host == RT_NULL)
                 {
                     rt_kprintf("Can't allocate memory for host.");
                 }
                 client_id = rt_malloc(100);
                 if (client_id == RT_NULL)
                 {
                     rt_kprintf("Can't allocate memory for client_id.");
                 }
                 user_name = rt_malloc(40);
                 if (user_name == RT_NULL)
                 {
                     rt_kprintf("Can't allocate memory for user_name.");
                 }
                 password = rt_malloc(40);
                 if (password == RT_NULL)
                 {
                     rt_kprintf("Can't allocate memory for password.");
                 }
                 uint32_t mcu_id[3];
                 get_device_id(mcu_id);
                 rt_sprintf(device_name, "%08X%08X%08X",mcu_id[0],mcu_id[1],mcu_id[2]);
                 cJSON *ProductKey = cJSON_GetObjectItem(root, "ProductKey");
                 strcpy(product_key, ProductKey->valuestring);
                 cJSON *DeviceSecret = cJSON_GetObjectItem(root, "DeviceSecret");
                 strcpy(device_secret, DeviceSecret->valuestring);
                 cJSON *Region = cJSON_GetObjectItem(root, "Region");
                 strcpy(region, Region->valuestring);
                 mqtt_log_init();
                 my_client = mqtt_lease();
                 rt_sprintf(host, "%s.iot-as-mqtt.%s.aliyuncs.com", product_key, region);
                 mqtt_set_host(my_client, host);
                 mqtt_set_port(my_client, "1883");
                 rt_sprintf(client_id, "%s|securemode=3,signmethod=hmacsha1|", device_name);
                 mqtt_set_client_id(my_client, client_id);
                 rt_sprintf(user_name, "%s&%s", device_name, product_key);
                 mqtt_set_user_name(my_client, user_name);
                 char sign[128];
                 unsigned char hmacsha1[20];
                 rt_sprintf(sign, "clientId%sdeviceName%sproductKey%s", device_name, device_name, product_key);
                 tiny_sha1_hmac((unsigned char *)device_secret, strlen(device_secret), (unsigned char*)&sign, strlen(sign), hmacsha1);
                 int password_length;
                 rt_memset(password, '\0', sizeof(password));
                 hex2string((char *)&hmacsha1, password, sizeof(hmacsha1), &password_length);
                 mqtt_set_password(my_client, password);
//                 LOG_I("host: %s\n", host);
//                 LOG_I("client_id: %s\n", client_id);
//                 LOG_I("user_name: %s\n", user_name);
//                 LOG_I("password: %s\n", password);
                 mqtt_set_clean_session(my_client, 1);
                 mqtt_set_keep_alive_interval(my_client, 180);
                 mqtt_set_reconnect_try_duration(my_client, 2048);
                 mqtt_connect(my_client);
             }
             //释放json
             cJSON_Delete(root);
        }
    }
__mqtt_config_exit:
    if(buffer)
    {
        rt_free(buffer);
        buffer = RT_NULL;
    }

}

void check_rtu(void)
{
    int fd, size;
    char *buffer = RT_NULL;
    int ret;
    struct stat buf;

    cJSON *root = RT_NULL;
    cJSON *item = RT_NULL, *item1 = RT_NULL;
    int array_size = 0;

    ret = stat("/rtu.json", &buf);
    if(ret == 0)
    {
        buffer = rt_malloc(buf.st_size);
        /* 以只读模式打开文件 */
        fd = open("/rtu.json", O_RDONLY);
        if (fd >= 0)
        {
             size = read(fd, buffer, buf.st_size);
             close(fd);
             if (size < 0)
             {
                 return ;
             }
             root = cJSON_Parse(buffer);
             if (!root)
             {
                 printf("Error before: [%s]\n",cJSON_GetErrorPtr());
             }
             else
             {
                 array_size = cJSON_GetArraySize(root);
                 for(uint16_t i = 0; i < array_size; i++)
                 {
                     item = cJSON_GetArrayItem(root, i);
                     item1 = cJSON_GetObjectItem(item, "PARTY_ID");
                     //item1->valuestring;
                 }
             }
        }
    }
}
